package org.example.yuaiagent.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.example.yuaiagent.common.Result;
import org.example.yuaiagent.model.entity.User;
import org.example.yuaiagent.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServiceImpl userService;
    @RequestMapping("/getUserInfo")
    public Result getUserInfo(String id){
        User safetyUser = userService.getSafetyUser(id);
        return Result.ok("获取用户信息成功", safetyUser);
    }
    @PostMapping("/login")
    public Result login(@RequestBody User  user,HttpServletResponse response){
        User u = userService.userLogin(user);
        response.setHeader("Authorization", "Bearer " + u.getId());
        return Result.ok("登录成功", u);
    }

    @PostMapping("/logout")
    public Result logout(@RequestBody User user){
        userService.userLogout(user);
        return Result.ok("登出成功", null);
    }
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        //参数校验
        if (user == null) {
            return Result.fail("参数错误", null);
        };
        if (user.getUsername() == null || user.getUsername().isEmpty()
                || user.getPassword() == null || user.getPassword().isEmpty()) {
            return Result.fail("参数错误", null);
        };
        User u = userService.userRegister(user);
        if (u == null) {
            return Result.fail("注册失败", null);
        };
        return Result.ok("注册成功", null);
    }
    @PostMapping("/update")
    public Result update(@RequestBody User user){
        if (user == null || user.getId() == null || user.getId().isEmpty()
                || user.getUsername() == null || user.getUsername().isEmpty()
                || user.getPassword() == null || user.getPassword().isEmpty()) {
            return Result.fail("参数错误", null);
        };
        userService.updateById(user);
        return Result.ok("更新成功", null);
    }

}
